package com.kingdee.fpy;/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.pdfbox.io.*;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * This is the in-memory representation of the PDF document.
 * The #close() method must be called once the document is no longer needed.
 * 
 * @author Ben Litchfield
 */
public class PDDocumentFpy extends PDDocument implements Closeable
{
    public static PDDocument load(File file) throws IOException
    {
        @SuppressWarnings({"squid:S2095"}) // raFile not closed here, may be needed for signing
        RandomAccessBufferedFileInputStream raFile = new RandomAccessBufferedFileInputStream(file);
        try
        {
            return load(raFile, "", null, null,  MemoryUsageSetting.setupMainMemoryOnly());
        }
        catch (IOException ioe)
        {
            IOUtils.closeQuietly(raFile);
            throw ioe;
        }
    }

    public static PDDocument load(byte[] input) throws IOException
    {
        ScratchFile scratchFile = new ScratchFile(MemoryUsageSetting.setupMainMemoryOnly());
        RandomAccessRead source = new RandomAccessBuffer(input);
        PDFParser parser = new PDFParserFpy(source, "", null, null, scratchFile);
        parser.parse();
        return parser.getPDDocument();
    }


    public static PDDocument load(InputStream input, String password, InputStream keyStore,
                                  String alias, MemoryUsageSetting memUsageSetting) throws IOException
    {
        ScratchFile scratchFile = new ScratchFile(memUsageSetting);
        try
        {
            RandomAccessRead source = scratchFile.createBuffer(input);
            PDFParser parser = new PDFParserFpy(source, password, keyStore, alias, scratchFile);
            parser.parse();
            return parser.getPDDocument();
        }
        catch (IOException ioe)
        {
            IOUtils.closeQuietly(scratchFile);
            throw ioe;
        }
    }
}
